import processing.video.*;

Capture cam;
PImage pic;
int cols, rows;

void setup() {
  size(640, 480);
  String[] cameras = Capture.list();
  println("cameras:");
  printArray(cameras);
  cam = new Capture(this, cameras[0]);
  cam.start();      
  delay(2000);
}

void draw() {
  if (cam.available() == true) {
    cam.read();
    pic = cam.copy();
    imgprocess();
  }
  //image(cam, 0, 0);
  image(pic, 0, 0);

}

int constrainX(int x) {
  int result = 0;
  int min = 0, max = 640;
  if (x>=min && x<=max) {
    result = x;
  }
  else if(x<=min) {
    result = min;
  }
  else {
    result = max;
  }
  return result;
}

int constrainY(int y) {
  int result = 0;
  int min = 0, max = 480;
  if (y>=min && y<=max) {
    result = y;
  }
  else if(y<=min) {
    result = min;
  }
  else {
    result = max;
  }
  return result;
}

int pos = 0;

int getPos(int x,int y) {
  int result = 0;
  x = constrainX(x);
  y = constrainY(y);
  
  result = y*pic.width+x;
  return result;
}

void imgprocess() {
  pic.loadPixels();
  for (int y=0; y<pic.height; y++) {
    for (int x=0; x<pic.width; x++) {
      pos = getPos(x,y);
      int G = (pic.pixels[pos] >> 8) & 0xFF;
      pic.pixels[pos] = 0;
      if (G > 200)
      {
        pic.pixels[pos] = 0x00ff00;
      }
    }
  }
  pic.updatePixels();
  
  
}
